package com.qy566.gps.pulsar.producer;

import com.alibaba.fastjson.JSON;
import com.qy566.gps.common.base.exceptions.ValidException;
import com.qy566.gps.common.base.logs.GpsLogger;
import com.qy566.gps.common.pulsar.errors.PulsarError;
import com.qy566.gps.common.pulsar.producer.PulsarTemplate;
import com.qy566.gps.pulsar.entidy.Position;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class ProducerService {

    @Autowired
    private PulsarTemplate<String> Producers;


    public void sendPulsar(String topicName, String msg) throws PulsarClientException {
        if (topicName == null && msg == null) {
            return;
        }
        Producers
                .createMessage(topicName, msg)
                .send();
        GpsLogger.busLogger().info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "消息发送Topic:" + topicName + " 成功,消息内容： " + msg);
    }

    public void sendPosition(Position position) {
        position.setAccuracy(0.0);
        position.setAltitude(0.0);
        position.setAttributes("{\"ignition\":true}");
        position.setCourse(0.0);
        position.setDataSource("JT808");
        position.setFixtime(new Date());
        position.setIndex(2);
        position.setAddress("山西省太原市小店区");
        if (position.getSpeed() == 0) {
            position.setSpeed(50.1);
        }
        position.setType("POSITION");
        position.setValid(true);
        try {
            Producers
                    .createMessage("positionTopic", JSON.toJSONString(position))
                    .send();
            GpsLogger.busLogger().info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "消息发送Topic:positionTopic 成功,消息内容： " + JSON.toJSONString(position));
        } catch (Exception e) {
            throw new ValidException(PulsarError.PULSAR_PRODUCER_ERROR, e);
        }
    }


    public void generateCarNo(String key, Position position) {
        int count = 0;
        ExecutorService executorService = Executors.newFixedThreadPool(200);
        for (int i = 0; i <= 0; i++) { // 第一位数字
            for (int j = 0; j <= 4; j++) { // 第二位数字
                for (int k = 0; k <= 9; k++) { // 第三位数字
                    for (int l = 0; l <= 9; l++) { // 第四位数字
                        for (int m = 0; m <= 9; m++) { // 第四位数字
                            if (i == 0 && j == 0 && k == 0 && l == 0 && m == 0) {
                                continue; // 跳过鲁B00000
                            }
                            final int finalI = i;
                            final int finalJ = j;
                            final int finalK = k;
                            final int finalL = l;
                            final int finalM = m;

                            double latitude = position.getLatitude();
                            double longitude = position.getLongitude();
                            executorService.submit(() -> {
                                Position position1 = new Position(); // 为每个任务创建一个新的Position对象
                                String carNo = "鲁" + key + finalI + finalJ + finalK + finalL + finalM;
                                position1.setCarNo(carNo);
                                position1.setLatitude(latitude);
                                position1.setLongitude(longitude);
                                position1.setDeviceCode("0000000" + finalI + finalJ + finalK + finalL + finalM);
                                try {
                                    sendPosition(position1);
                                } catch (Exception e) {
                                    GpsLogger.busLogger().error("消息发送Topic:positionTopic 失败,失败原因： " + e.getMessage());
//                                return new BaseResponse<>(PulsarError.PULSAR_PRODUCER_ERROR, e.getMessage());
                                }
                            });
                            GpsLogger.busLogger().info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "消息发送次数: " +count);
                            count++;
                        }
                    }
                }
            }
        }

        // 关闭线程池并等待所有任务完成
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)) {
                GpsLogger.busLogger().error("线程关闭失败或超时===============================");
            }
        } catch (InterruptedException e) {
            // 如果当前线程在等待过程中被中断，你可以选择处理这种情况（例如，通过恢复中断状态或抛出异常）
            GpsLogger.busLogger().error("线程在等待过程中被中断===============================" + e.getMessage());
            Thread.currentThread().interrupt();
        }
    }
}
